package com.tongda.core.service;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;

import org.springframework.http.ResponseEntity;

import android.content.Context;
import android.util.Log;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tongda.core.common.Constants;
import com.tongda.core.enums.DishesTypeEnum;
import com.tongda.core.enums.StatusCodeEnum;
import com.tongda.core.repository.DishCategoryDAO;
import com.tongda.core.repository.DishDao;
import com.tongda.core.repository.MenuDishCategoryDAO;
import com.tongda.core.repository.MenuDishDao;
import com.tongda.core.utils.CommunicationUtil;
import com.tongda.core.utils.SharedPreferencesUtils;
import com.tongda.core.vo.Dish;
import com.tongda.core.vo.DishesCategory;
import com.tongda.core.vo.MobileRspResult;

public class DishService extends BaseService {

	public static Map codeMap;

	static {
		codeMap = new HashMap();
		codeMap.put("A", "2");
		codeMap.put("B", "2");
		codeMap.put("C", "2");
		codeMap.put("D", "3");
		codeMap.put("E", "3");
		codeMap.put("F", "3");
		codeMap.put("G", "4");
		codeMap.put("H", "4");
		codeMap.put("I", "4");
		codeMap.put("J", "5");
		codeMap.put("K", "5");
		codeMap.put("L", "5");
		codeMap.put("M", "6");
		codeMap.put("N", "6");
		codeMap.put("O", "6");
		codeMap.put("P", "7");
		codeMap.put("Q", "7");
		codeMap.put("R", "7");
		codeMap.put("S", "7");
		codeMap.put("T", "8");
		codeMap.put("U", "8");
		codeMap.put("V", "8");
		codeMap.put("W", "9");
		codeMap.put("X", "9");
		codeMap.put("Y", "9");
		codeMap.put("Z", "9");
		codeMap.put("0", "0");
		codeMap.put("1", "1");
		codeMap.put("2", "2");
		codeMap.put("3", "3");
		codeMap.put("4", "4");
		codeMap.put("5", "5");
		codeMap.put("6", "6");
		codeMap.put("7", "7");
		codeMap.put("8", "8");
		codeMap.put("9", "9");
	}

	/**
	 * 点餐宝同步菜类
	 */
	public static MobileRspResult synchronizeDishCategary(Context context) {
		ResponseEntity<MobileRspResult> responseEntity = BaseService.get(
				"mobile/dishe/getAllDisheCategorys", MobileRspResult.class,
				null);
		if (responseEntity != null) {
			MobileRspResult r = responseEntity.getBody();
			if (r.getStatusCode().equals(StatusCodeEnum.SUCCESS.getCode())) {
				List<DishesCategory> categoryList = Arrays
						.asList(parseObjectToT(r.getObject(),
								DishesCategory[].class));
				DishCategoryDAO dishCategoryDAO = DishCategoryDAO
						.getInstance(context);
				dishCategoryDAO.initInsert(categoryList);
				return r;
			}
		}
		return new MobileRspResult(StatusCodeEnum.CONNECT_ERROR.getCode(),
				StatusCodeEnum.CONNECT_ERROR.getDesc() + "获取菜类失败", null);
	}

	/**
	 * 电子菜谱同步菜类
	 */
	public static MobileRspResult synchronizeMenuDishCategary(Context context) {
		ResponseEntity<MobileRspResult> responseEntity = BaseService.get(
				"mobile/dishe/getAllDisheCategorys", MobileRspResult.class,
				null);
		if (responseEntity != null) {
			MobileRspResult r = responseEntity.getBody();
			if (r.getStatusCode().equals(StatusCodeEnum.SUCCESS.getCode())) {
				List<DishesCategory> categoryList = Arrays
						.asList(parseObjectToT(r.getObject(),
								DishesCategory[].class));
				MenuDishCategoryDAO dishCategoryDAO = MenuDishCategoryDAO
						.getInstance(context);
				dishCategoryDAO.clearDishCategory();
				dishCategoryDAO.buildInsert(categoryList);
				return r;
			}
		}
		return new MobileRspResult(StatusCodeEnum.CONNECT_ERROR.getCode(),
				StatusCodeEnum.CONNECT_ERROR.getDesc() + "获取菜类失败", null);
	}

	/**
	 * 电子菜谱同步菜肴
	 */
	public static List<Dish> synchronizeMenuDish(Context context) {
		List<Dish> ds = new ArrayList<Dish>();
		synchronized (context) {
			MenuDishDao dishDao = MenuDishDao.getInstance(context);
			dishDao.clearDish();
			ObjectMapper objectMapper = new ObjectMapper();
			String jsonStr = CommunicationUtil.get(Constants.BASE_SERVIER_URL
					+ "mobile/dishe/getAllDishes" + "?onlyShownInRest=" + "1");
			Dish[] arr = null;
			try {
				// 忽略一些属性对应不上的代码
				// objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
				arr = objectMapper.readValue(jsonStr, Dish[].class);
			} catch (Exception e) {
				e.printStackTrace();
				Log.e("getAllDishes", e.toString());
				return ds;
			}
			ds = Arrays.asList(arr);
		}
		return ds;
	}

	/**
	 * 同步菜谱
	 */
	public static int synchronizeDish(Context context) {
		int i = 0;
		// 先清空菜谱
		synchronized (context) {
			DishDao dishDao = DishDao.getInstance(context);
			// 插入新菜谱
			ObjectMapper objectMapper = new ObjectMapper();
			String jsonStr = CommunicationUtil.get(Constants.BASE_SERVIER_URL
					+ "mobile/bill/getalldish");
			Dish[] arr = null;
			try {
				arr = objectMapper.readValue(jsonStr, Dish[].class);
				List<Dish> ds = Arrays.asList(arr);
				dishDao.initInsert(ds);
				if (arr != null && dishDao.getCount() == arr.length) {
					i = 1;
				}
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return i;
	}

	/**
	 * 构建菜谱的数字查询编码
	 * 
	 * @param dish
	 * @return
	 */
	public static Dish buildSearchCode(Dish dish) {
		StringBuffer buff = new StringBuffer();
		String dishesCode = dish.getDishesCode();
		char[] arr = dishesCode.toCharArray();
		for (int i = 0; i < arr.length; i++) {
			char c = arr[i];
			String str = String.valueOf(c).toUpperCase();
			buff.append(codeMap.get(str));
		}
		dish.setSearchCode(buff.toString());
		return dish;
	}

	/**
	 * 根据数字查询菜肴
	 * 
	 * @param context
	 * @param code
	 * @return
	 */
	public static List<Dish> findDishesByCode(Context context, String code) {
		DishDao dishDao = DishDao.getInstance(context);
		List<Dish> dishes = null;
		List<String> highlightCode = null;
		if (code != null && !code.equals("")) {
			try {
				dishes = dishDao.searchBySearchCodes(code);
			} catch (Exception e) {
				e.printStackTrace();
				return new ArrayList<Dish>();
			}
			if (dishes != null && dishes.size() > 0) {
				// 处理高亮问题
				for (Dish dish : dishes) {
					String searchCode = dish.getSearchCode();
					int offset = 0;
					if (searchCode.indexOf(code) != -1) {
						highlightCode = new ArrayList<String>();
						while (searchCode.indexOf(code) != -1) {
							String start = String.valueOf(searchCode
									.indexOf(code) + offset);
							String end = String
									.valueOf(searchCode.indexOf(code)
											+ code.length() - 1 + offset);
							highlightCode.add(start + ";" + end);
							offset = offset + searchCode.indexOf(code)
									+ code.length();
							searchCode = searchCode.substring(
									searchCode.indexOf(code) + code.length(),
									searchCode.length());
						}
						dish.setHighlightCode(highlightCode);
					}
				}
			}
		}
		return dishes;
	}

	/**
	 * 点餐 加菜
	 * 
	 * @param dishId
	 * @param unitNum
	 */
	public static MobileRspResult orderDish(String billId, String dishId,
			String unitNum, String isJudgeRm) {
		ResponseEntity<MobileRspResult> responseEntity = BaseService.postUrl(
				"mobile/bill/jiacai" + "?billId=" + billId + "&dishId="
						+ dishId + "&unitNum=" + unitNum + "&isJudgeRm="
						+ isJudgeRm, MobileRspResult.class);
		if (responseEntity != null) {
			MobileRspResult r = responseEntity.getBody();
			if (r.getStatusCode().equals(StatusCodeEnum.SUCCESS.getCode())) {
				Map<String, String> map = parseObjectToT(r.getObject(),
						HashMap.class);
				r.setMap(map);
				return r;
			} else {
				return responseEntity.getBody();
			}
		}
		return new MobileRspResult(StatusCodeEnum.ERROR.getCode(), "失败", "");
	}

	/**
	 * 点餐 加菜(套餐)
	 * 
	 * @param dishId
	 * @param unitNum
	 */
	public static MobileRspResult orderDishSet(String billId, String dishId,
			String unitNum, String dsDishesDesc, String isJudgeRm) {
		ResponseEntity<MobileRspResult> responseEntity = BaseService.postUrl(
				"mobile/bill/jiacaiSet" + "?billId=" + billId + "&dishId="
						+ dishId + "&unitNum=" + unitNum + "&dsDishesDesc="
						+ dsDishesDesc + "&isJudgeRm=" + isJudgeRm,
				MobileRspResult.class);
		if (responseEntity != null) {
			MobileRspResult r = responseEntity.getBody();
			if (r.getStatusCode().equals(StatusCodeEnum.SUCCESS.getCode())) {
				Map<String, String> map = parseObjectToT(r.getObject(),
						HashMap.class);
				r.setMap(map);
				return r;
			} else {
				return responseEntity.getBody();
			}
		}
		return new MobileRspResult(StatusCodeEnum.ERROR.getCode(), "失败", "");
	}

	/**
	 * 获取菜肴沽清
	 * 
	 * @param value
	 * @return
	 */
	public static Float getDishEstimate(String value, String isSet) {
		Map<String, Object> params = new WeakHashMap<String, Object>();
		params.put("id", value);
		params.put("isSet", isSet);
		ResponseEntity<Float> responseEntity = BaseService.get(
				"mobile/bill/getDishEstimate", Float.class, params);
		if (responseEntity != null) {
			return responseEntity.getBody();
		}
		// return -1f;
		return -3f;
	}

	/**
	 * 验证是否是有效的特价菜，如果是有效的特价菜则返回符合条件的最小特价价格，如果不是则返回null
	 */
	public static BigDecimal judgePrice(String disheId, String dishesType,
			String creatTimeStr) {
		Map<String, Object> params = new WeakHashMap<String, Object>();
		params.put("disheId", disheId);
		if (dishesType.equals("false")) {
			params.put("dishesType", DishesTypeEnum.DISHES.getCode());
		} else if (dishesType.equals("true")) {
			params.put("dishesType", DishesTypeEnum.DISHES_SET.getCode());
		}
		params.put("creatTimeStr", creatTimeStr);
		ResponseEntity<MobileRspResult> responseEntity = BaseService
				.get("mobile/dishe/judgeSpecialPrice", MobileRspResult.class,
						params);
		if (responseEntity != null) {
			MobileRspResult r = responseEntity.getBody();
			if (r.getStatusCode().equals(StatusCodeEnum.SUCCESS.getCode())) {
				if (r.getObject() != null) {
					BigDecimal spPrice = BigDecimal.valueOf((Double) r
							.getObject());
					return spPrice;
				}
			}
		}
		return null;
	}

	/**
	 * 点餐 加菜(套餐)
	 * 
	 * @param dishId
	 * @param unitNum
	 */
	public static String orderDishSet(String billId, String dishId,
			String unitNum, String isJudgeRm) {
		String dinerBillDisheId = CommunicationUtil
				.get(Constants.BASE_SERVIER_URL + "mobile/bill/jiacaiSet"
						+ "?billId=" + billId + "&dishId=" + dishId
						+ "&unitNum=" + unitNum + "&isJudgeRm=" + isJudgeRm);
		return dinerBillDisheId;
	}

	/**
	 * 点餐 加菜
	 * 
	 * @param dishId
	 * @param unitNum
	 */
	public static String orderDish(String billId, String dishId,
			String unitNum, String isJudgeRm, String isRulingPrice,
			String rulingPrice) {
		String dinerBillDisheId = CommunicationUtil
				.get(Constants.BASE_SERVIER_URL + "mobile/bill/jiacai"
						+ "?billId=" + billId + "&dishId=" + dishId
						+ "&unitNum=" + unitNum + "&isJudgeRm=" + isJudgeRm
						+ "&isRulingPrice=" + isRulingPrice + "&rulingPrice="
						+ rulingPrice);
		return dinerBillDisheId;
	}
	
	public static Date toDate(String dateStr){
		dateStr = dateStr.trim();
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		 Date date = null;
		try {
			date = sdf.parse(dateStr);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date; 
	}

	public static boolean isUpdateDish(Context ctx) {
		
		String clientLastUpdateTimeStr = (String)SharedPreferencesUtils.getParam(ctx, "clientLastUpdateTimeStr", String.valueOf(toDate("1970-01-01 00:00:00").getTime()));
		ResponseEntity<MobileRspResult> responseEntity = BaseService.postUrl(
				"mobile/dishe/checkDishChange?clientLastUpdateTimeStr="+clientLastUpdateTimeStr,
				MobileRspResult.class);
		if (responseEntity != null) {
			MobileRspResult r = responseEntity.getBody();
			if (r.getStatusCode().equals(StatusCodeEnum.SUCCESS.getCode())) {
				Map<String, String> map = parseObjectToT(r.getObject(),
						HashMap.class);
				r.setMap(map);
				String isUpdateDish = map.get("isUpdateDish");
				String clientLastUpdateTime = map.get("clientLastUpdateTimeStr");
				if("1".equals(isUpdateDish))
				{
					SharedPreferencesUtils.setParam(ctx, "clientLastUpdateTimeStr", clientLastUpdateTime);
					return true;
				}
				else
				{
					return false;
				}
			} else {
				return false;
			}
		}
		return false;
	}
	
	/**
	 * 更改时价菜价格
	 * */
	public static MobileRspResult updateRulingPrice(String dishId,BigDecimal rulingPrice){
		Map<String, Object> params = new WeakHashMap<String,Object>();
		params.put("dishId", dishId);
		params.put("rulingPrice", rulingPrice);
		ResponseEntity<MobileRspResult> result = BaseService.get("mobile/dishe/updateRulingPrice", MobileRspResult.class, params);
		if(result!=null){
			if(result.getStatusCode().equals(StatusCodeEnum.SUCCESS.getCode())){
				return new MobileRspResult(StatusCodeEnum.SUCCESS.getCode(), "更改时价价格成功", null);
			}
		}
		return new MobileRspResult(StatusCodeEnum.ERROR.getCode(), "更改时价价格失败", null);
	}
}
